package com.kangyi.user.sms;

import com.kangyi.constant.MessageConstant;
import com.kangyi.exception.SendMessageException;

import com.kangyi.utils.HttpUtils;
import com.kangyi.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Blank
 * @version 1.0
 */
@Slf4j
public class SmsServer {

    private final RedisTemplate<String, String> redisTemplate;


    // 最小请求间隔，单位：秒（例如 60 秒即 1 分钟）
    private static final long REQUEST_INTERVAL = 60L;

    // 构造器注入 RedisTemplate
    public SmsServer(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 发送短信
    public void sendSms(String phone) {

        // 检查是否频繁请求
        if (isFrequentRequest(phone)) {
            throw new SendMessageException(MessageConstant.CAPTCHA_FREQUENT);
        }

        boolean mobile = isMobile(phone);
        if (!mobile) {
            throw new SendMessageException(MessageConstant.MOBILE_FAILED);
        }

        String randomCode = WebUtil.randomCode(6);  // 生成验证码

        log.info("发送短信的手机号码是：{}", phone);
        log.info("生成的验证码是：{}", randomCode);


        String host = "https://zwp.market.alicloudapi.com";
        String path = "/sms/sendv2";
        String method = "GET";
        String appcode = "e8eb99d0ed8b4d8689351f6de7d7a5ff";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("content", "【智能云】您的验证码是"+randomCode+"。如非本人操作，请忽略本短信");

        try {
            // 调用短信 API 发送短信
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            log.info("短信发送响应: {}", response.toString());

            // 将验证码存储到 Redis，设置过期时间为 10 分钟
            redisTemplate.opsForValue().set(phone, randomCode, 10, TimeUnit.MINUTES);

            // 更新请求时间戳，限制 1 分钟内不能重复申请
            redisTemplate.opsForValue().set("sms_request_time:" + phone, String.valueOf(System.currentTimeMillis()));
        } catch (Exception e) {
            log.error("发送短信失败{}", e);
        }

    }

    // 检查是否频繁请求
    private boolean isFrequentRequest(String phone) {
        String key = "sms_request_time:" + phone;
        String lastRequestTime = redisTemplate.opsForValue().get(key);

        if (lastRequestTime == null) {
            // 如果没有请求记录，说明是第一次请求
            return false;
        }

        long lastRequestTimestamp = Long.parseLong(lastRequestTime);
        long currentTimestamp = System.currentTimeMillis();

        // 如果距离上次请求时间小于 REQUEST_INTERVAL（60 秒），则认为是频繁请求
        return (currentTimestamp - lastRequestTimestamp) < (REQUEST_INTERVAL * 1000);
    }

    // 验证验证码
    public boolean verifyCode(String phone, String code) {
        String cachedCode = redisTemplate.opsForValue().get(phone);
        return cachedCode != null && cachedCode.equals(code);
    }

    public static boolean isMobile(final String phone){
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }
}
